#include "wallperwidget.h"
#include "ui_wallperwidget.h"

#include "xutil.h"
#include <windows.h>
#include <QDebug>
#include <QDir>
#include <QMessageBox>
#include <QStringListModel>
#include <QStyledItemDelegate>
#include <QToolTip>

WallperWidget::WallperWidget(QWidget *parent) : QWidget(parent), ui(new Ui::WallperWidget)
{
    ui->setupUi(this);
    this->setWindowTitle("设置壁纸");
    QStringListModel *model = new QStringListModel(this);

    ui->wallpaperListView->setModel(model);

    ui->wallpaperListView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    //设置提示
    // 启用鼠标跟踪以接收鼠标移动事件，这个设置后tooltip显示效果好了很多
    ui->wallpaperListView->setMouseTracking(true);
    //这个效果不知道是啥
    ui->wallpaperListView->setItemDelegate(new QStyledItemDelegate(this));
    connect(ui->wallpaperListView, &QListView::entered, [this](auto idx) {
        //        qDebug() << "clicked:" << idx;
        if (idx.isValid()) {
            // 假设我们想为每个项目添加一个简单的 tooltip

            // QString tooltipText = model->data(idx).toString();
            ui->wallpaperListView->setToolTip(idx.data().toString());
        } else {
            //            ui->wallpaperListView->setToolTip("");
            QToolTip::hideText();
        }
    });

    updateWallapperListView();

    //随机选择一个图片显示在label里
    auto picPaths = model->stringList();
    if (!picPaths.isEmpty()) {
        auto picPath = picPaths[xNextRandom(picPaths.size())];
        ui->wallpaperLabel->setPixmap(
            QPixmap(picPath).scaled(400, 300, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        ui->wallpaperLabel->setProperty("currentPic", picPath);
    }
}

WallperWidget::~WallperWidget()
{
    delete ui;
}

QStringList listAllFiles(QString dirPath)
{
    QStringList files;

    QDir d(dirPath);

    auto ls = d.entryInfoList();

    foreach (const auto &f, ls) {
        if (!f.fileName().endsWith(".")) {
            if (f.isDir()) {
                files << listAllFiles(f.filePath());
            } else {
                files << f.absoluteFilePath();
            }
        }
    }
    return files;
}

QStringList listAllWallpapers()
{
    QStringList walls;
    walls << listAllFiles("wallpaper");
    walls << listAllFiles(R"(C:\Windows\Web\Wallpaper)");
    //    qDebug() << walls;
    return walls;
}

void WallperWidget::updateWallapperListView()
{
    auto m = qobject_cast<QStringListModel *>(ui->wallpaperListView->model());

    m->setStringList(listAllWallpapers());
}

bool WallperWidget::setWallpaperWithWinAPI(const QString &imagePath)
{
    // 将QString转换为LPWSTR
    wchar_t widePath[MAX_PATH];
    imagePath.toWCharArray(widePath);
    widePath[imagePath.size()] = 0; // 确保以null结尾

    // 设置壁纸
    WINBOOL b = SystemParametersInfoW(SPI_SETDESKWALLPAPER,
                                      0,
                                      widePath,
                                      SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
    //    qDebug() << "winbool = " << b;

    if (!b) {
        QMessageBox::warning(this, "设置壁纸", "设置壁纸失败");
    }

    return true;
}

//bool restoreDefaultWallpaper()
//{
//    wchar_t widePath[MAX_PATH] = L"";

//    // 方法1：传递空字符串
//    BOOL result1 = SystemParametersInfoW(SPI_SETDESKWALLPAPER,
//                                         0,
//                                         widePath,
//                                         SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

//    // 方法2：删除注册表项（更彻底）
//    //    HKEY hKey;
//    //    if (RegOpenKeyExW(HKEY_CURRENT_USER,
//    //                     L"Control Panel\\Desktop",
//    //                     0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
//    //        RegDeleteValueW(hKey, L"Wallpaper");
//    //        RegCloseKey(hKey);
//    //    }

//    // 再次调用确保生效
//    BOOL result2 = SystemParametersInfoW(SPI_SETDESKWALLPAPER,
//                                         0,
//                                         widePath,
//                                         SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

//    qDebug() << result1 << " - " << result2;

//    return result1 || result2;
//}

void WallperWidget::on_wallpaperListView_clicked(const QModelIndex &index)
{
    if (index.isValid()) {
        auto p = index.data(Qt::DisplayRole).toString();
        ui->wallpaperLabel->setPixmap(
            QPixmap(p).scaled(400, 300, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        ui->wallpaperLabel->setProperty("currentPic", p);
    }
}

void WallperWidget::on_setWallpaper_clicked()
{
    setWallpaperWithWinAPI(ui->wallpaperLabel->property("currentPic").toString());
}
